<template>
  <div v-page-show="{
    show:
      operate?.getOperate().checkedProject &&
      operate?.getOperate().openFunc?.includes(1),
    text: operate?.getOperate().checkedProject
      ? `暂未开通巡检功能`
      : '请先选择项目'
  }">
    <RePage>
      <MyFormCreate :clear-event="getTableList" v-model="searchFrom" :rule="searchFormRules" :key="key">
        <template #field-createdAt="scope">
          <el-form-item>
            <el-date-picker type="daterange" range-separator="至" start-placeholder="开始时间" end-placeholder="结束时间"
              value-format="YYYY-MM-DD" placeholder="请选择创建时间" style="width: 100%" v-model="searchFrom.createdAt"
              @change="dateChange" />
          </el-form-item>
        </template>
        <el-button type="primary" @click="DebounceGetTableList">搜索</el-button>

        <sj-button custom-type="sinfo" @click="DebounceResetting">重置</sj-button>
      </MyFormCreate>
      <div>
        <!-- <el-button type="primary" :icon="Plus" @click="add">添加</el-button> -->
        <el-button v-auth="'business.inspect.insp.remove'" type="danger" :disabled="!selectionData.length"
          @click="deletes()">批量删除</el-button>
      </div>
      <pure-table class="mt-5" :data="tableData.data" :columns="initPureTableConfig(roleTableConfig)" showOverflowTooltip border
        @selection-change="selectionChange" :isShowPag="false">
        <template #missionStatus="{ row }">
          <el-tag :type="INSPECTIONSTATUS1TEXT[row.missionStatus]?.type" 
         >{{
            isNullOrEmpty( INSPECTIONSTATUS1TEXT[row.missionStatus]?.label ) }}</el-tag>
          <!-- <span :style="{
    color: INSPECTIONSTATUS1TEXT[row.missionStatus]?.color
  }">
            {{ isNullOrEmpty( INSPECTIONSTATUS1TEXT[row.missionStatus]?.label ) }}
          </span> -->
        </template>
        <template #cycleValue="{ row }">
          <div>
            {{ isNullOrEmpty( row.cycleValue ) }} {{ isNullOrEmpty( PERIODUNITTEXT[row.cycleUnit]?.label ) }}
          </div>
        </template>
        <template #inspectResult="{ row }">
          <div v-if="row.missionStatus !== 1">
            <span :class="row.inspectResult == 0 ? 'text-[#4cb61f]' : 'text-[#d22c2e]'">
              {{ isNullOrEmpty( row.inspectResult == 0 ? "正常" : `异常(${row.inspectResult})` ) }}</span>
          </div>
          <div v-else>--</div>
        </template>

        <template #action="{ row }">
          <el-space>
            <sj-link custom-type="sblue" :underline="false" @click="info(row)">查看</sj-link>
            <!-- <sj-link custom-type="sblue" :underline="false" @click="edit(row)">编辑</sj-link> -->
            <!-- <sj-link custom-type="sred" :underline="false" @click="deletes(row)">删除</sj-link> -->
          </el-space>
        </template>
      </pure-table>
      <div class="mt-5">
        <el-pagination v-model:current-page="searchFrom.page" v-model:page-size="searchFrom.limit" background
          :layout="PAGE_LAYOUT" :total="tableData.total" @size-change="getTableList" @current-change="getTableList" />
      </div>
    </RePage>
  </div>
</template>
<script lang="ts" setup>
import {isNullOrEmpty,initPureTableConfig} from '@/utils/functions'
import { usePageVariablesStoreHook } from "@/store/modules/pageVariables";
const operate = usePageVariablesStoreHook();
import MyFormCreate from "@/components/MyFormCreate/index.vue";
import RePage from "@/components/RePage/index.vue";
import ReTable from "@/components/ReTable/index.vue";
import editForm from "./form.vue";
import infos from "./info.vue";
import {
  INSPECTIONRESULT,
  PERIODUNITTEXT,
  INSPECTIONSTATUSS,
  INSPECTIONSTATUS1TEXT
} from "@/constant/dayly-inspection";
import { reactive, ref, h } from "vue";
import { PAGE_LAYOUT } from "@/constant";
import { Plus, Delete } from "@element-plus/icons-vue";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  getList,
  getInfo,
  addInfo,
  editInfo,
  deleteInfo
} from "@/api/operate/daily-inspection/Inspection-tasks/index";
import { getProjectInfo } from "@/api/operate/daily-inspection/Inspection-plan/index";
import { titles, defaultSearchForm, prompt, defaultInfoForm } from "./index";
import { addDialog } from "@/components/ReDialog";
import {
  cloneDeep,
  isAllEmpty,
  deviceDetection,
  debounce
} from "@pureadmin/utils";
import { message } from "@/utils/message";
import { customDebounce, customPromiseDebounce } from "@/utils/functions";
const route = useRoute()  // 获取路由参数
const searchFrom = ref(defaultSearchForm());
const key = ref(0);
const showInfo = ref();
const formRef = ref();
const tableData = reactive({
  data: [],
  total: 0
});

const searchFormRules = [
  {
    type: "select",
    field: "missionStatus",
    title: titles.missionStatus,
    value: null,
    options: INSPECTIONSTATUSS,
    props: {
      placeholder: prompt.missionStatus,
      clearable: true
    }
  },
  {
    type: "fieldComponent",
    field: "createdAt",
    title: titles.createdAt,
    value: null,
    props: {
      placeholder: prompt.createdAt,
      clearable: true
    }
  },
  {
    type: "select",
    field: "inspectResult",
    title: titles.inspectResult,
    value: null,
    options: INSPECTIONRESULT,
    props: {
      placeholder: prompt.inspectResult,
      clearable: true
    }
  },
  { type: "number", field: "page", title: "page", hidden: true },
  { type: "number", field: "limit", title: "limit", hidden: true }
];
const selectionData = ref([]);
const roleTableConfig = [
  { type: "selection", align: "left" },
  { prop: "id", label: titles.id, width:  100,align: "left" },
  { prop: "unityName", label: "所属单位", minWidth: 150 },
  { prop: "projectName", label: titles.projectName, minWidth: 100 },
  { prop: "missionName", label: titles.missionName, minWidth: 100 },
  { slot: "missionStatus", label: titles.missionStatus, minWidth: 90 },
  { slot: "cycleValue", label: titles.cycleValue, minWidth: 90 },
  { prop: "finishDate", label: titles.finishDate, minWidth: 100 },
  { slot: "inspectResult", label: titles.inspectResult, minWidth: 90 },
  { prop: "inspectUser", label: titles.inspectUser, minWidth: 90 },
  { prop: "dealCount", label: titles.dealCount, minWidth: 100 },
  { slot: "action", label: titles.action, width: 80, fixed: "right" }
];
onMounted(() => {
  if (route.query.missionStatus) {
    searchFrom.value.missionStatus =Number(route.query.missionStatus) 
    key.value++
  }
  getTableList()
});
// 获取列表数据
const getTableList = () => {
  getList(searchFrom.value).then(res => {
    if (res.code === 200) {
      tableData.data = res.result.data;
      tableData.total = res.result.total;
    }
  });
};
const dateChange = e => {
  console.log(e);
  if (e) {
    searchFrom.value.startDate = e[0];
    searchFrom.value.endDate = e[1];
  } else {
    searchFrom.value.startDate = '';
    searchFrom.value.endDate = '';
  }
  getTableList()
};
// 重置搜索栏
const resetting = () => {
  //点击重置按键
  Object.assign(searchFrom.value, defaultSearchForm());
  key.value++;
  getTableList();
};
// 详情
const info = row => {
  addDialog({
    title: `详情`,
    hideFooter: true,
    width: "1100px",
    draggable: true,
    fullscreen: deviceDetection(),
    props: {
      taskId: row.id
    },
    fullscreenIcon: true,
    closeOnClickModal: false,
    contentRenderer: () => h(infos, { ref: formRef }),
    openAutoFocus({ options, index }) {
      options.props = {
        isLoading: true,
        taskId: row.id,
        formInline: defaultInfoForm()
      };
      getInfo({ id: row.id })
        .then(res => {
          if (res.code == 200) {
            console.log(res.result, "xsss");
            showInfo.value = res.result;
            options.props.formInline = res.result;
          }
        })
        .finally(() => {
          options.props.isLoading = false;
        });
    }
  });
};
// 新增
const add = row => {
  showInfo.value = {};
  openDialog();
};
// 编辑
const edit = row => {
  showInfo.value = {};
  openDialog("编辑", row);
};
// 删除
const deletes = (row?) => {
  ElMessageBox.confirm(`确认删除${row ? "当前" : "选中的"}数据?`, "警告", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() => {
    deleteInfo({
      ids: row ? [row.id] : selectionData.value.map(item => item.id)
    }).then(res => {
      if (res.code == 200) {
        ElMessage({
          type: "success",
          message: "删除成功"
        });
        getTableList();
      }
    });
  });
};
// 开启弹窗
const openDialog = (title = "新增", row?: any) => {
  addDialog({
    title: `${title}`,
    width: "800px",
    draggable: true,
    fullscreen: deviceDetection(),
    fullscreenIcon: true,
    closeOnClickModal: false,
    contentRenderer: () => h(editForm, { ref: formRef }),
    openAutoFocus({ options, index }) {
      if (row) {
        options.props = {
          isLoading: true,
          formInline: defaultInfoForm()
        };
        getInfo({ id: row.id })
          .then(res => {
            if (res.code == 200) {
              showInfo.value = res.result;
              options.props.formInline = res.result;
            }
          })
          .finally(() => {
            options.props.isLoading = false;
          });
      } else {
        options.props = {
          isLoading: false,
          formInline: defaultInfoForm()
        };
      }
    },
    beforeSure: (done, { options }) => {
      const FormRef = formRef.value.getRef();
      const formData = options.props.formInline;
      function chores() {
        message(`操作成功`, {
          type: "success"
        });
        done(); // 关闭弹框
        getTableList(); // 刷新表格数据
      }
      FormRef.validate(valid => {
        if (valid && !options.props?.isLoading) {
          // console.log("formData", formData);
          // 表单规则校验通过
          options.props.isLoading = true;
          if (title === "新增") {
            DebounceAddInfo(formData)
              .then(res => {
                if (res.code == 200) {
                  chores();
                }
                options.props.isLoading = false;
              })
              .catch(err => {
                if (err !== "请求中") {
                  options.props.isLoading = false;
                }
              });
          } else {
            DebounceEditInfo(formData)
              .then(res => {
                if (res.code == 200) {
                  chores();
                }
                options.props.isLoading = false;
              })
              .catch(err => {
                if (err !== "请求中") {
                  options.props.isLoading = false;
                }
              });
          }
        }
      });
    }
  });
};
const selectionChange = data => {
  selectionData.value = data;
};
// 获取列表
const DebounceGetTableList = debounce(getTableList, 1000, true);
// 重置
const DebounceResetting = debounce(resetting, 1000, true);
// 添加请求
const DebounceAddInfo = customPromiseDebounce(addInfo, 1000, true);
// 编辑请求
const DebounceEditInfo = customPromiseDebounce(editInfo, 1000, true);
</script>
<style lang="scss" scoped>
::v-deep(.el-form-item__content) {
  display: block !important;
}
</style>
